package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

@Component("crmFromFormAuthenticationFilter")
public class AjaxFormAuthenticationFilter extends FormAuthenticationFilter {
    //登录成功的情况
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        JsonResult json = new JsonResult();
        //使用response传输数据(json字符串)
        response.setContentType("application/json;charset=utf-8");
        //使用写入流传到前端页面
        response.getWriter().print(JSON.toJSONString(json));
        return false;
    }

    //登录失败的情况

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        //后台打印异常
        e.printStackTrace();
        String msg = "登录异常,请联系管理员";
        if (e instanceof UnknownAccountException) {//如果是账号不存在
            msg="账号不存在";
        }else if(e instanceof IncorrectCredentialsException){
            msg="密码错误";
        }
        JsonResult json = new JsonResult(false,msg);
        //使用response传输数据(json字符串)
        response.setContentType("application/json;charset=utf-8");
        //使用写入流传到前端页面
        try {
            response.getWriter().print(JSON.toJSONString(json));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;//不放行
    }
}
